package com.bigzero.workflow.common.service.impl;

import com.bigzero.workflow.modules.system.service.UserService;
import com.bigzero.workflow.modules.system.vo.UserActivitiVo;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Activiti7配置文件-用户管理器
 * @author fanxinxiong
 * @date 2025-02-13 12:38
 */
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService{

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserActivitiVo vo = userService.getUserActivitiVoByUsername(username);
        vo = Optional.ofNullable(vo).orElse(new UserActivitiVo());
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if(!CollectionUtils.isEmpty(vo.getSimpleRoleList())){
            for(UserActivitiVo.SimpleRole simpleRole : vo.getSimpleRoleList()){
                authorities.add(new SimpleGrantedAuthority(simpleRole.getId()));
            }
        }
        //这里要填上用户的账号、密码(可以不填)和角色集合
        return new User(username, "", authorities);
    }
}
